package com.example.quartz.service;

import com.example.quartz.job.SampleJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Quartz 服务类，用于管理定时任务
 */
@Service
public class QuartzService {
    private static final Logger logger = LoggerFactory.getLogger(QuartzService.class);

    @Autowired
    private Scheduler scheduler;

    /**
     * 创建一个一次性执行的任务
     */
    public String createOneTimeJob() throws SchedulerException {
        // 生成唯一任务名
        String jobName = "oneTimeJob_" + System.currentTimeMillis();
        String jobGroup = "ONE_TIME_GROUP";
        
        // 定义任务
        JobDetail jobDetail = JobBuilder.newJob(SampleJob.class)
                .withIdentity(jobName, jobGroup)
                .withDescription("One time executed job")
                .storeDurably()
                .build();
        
        // 定义触发器 - 立即执行一次
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger_" + jobName, jobGroup)
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withRepeatCount(0))
                .build();
        
        // 提交任务
        Date scheduleDate = scheduler.scheduleJob(jobDetail, trigger);
        logger.info("已创建一次性任务: {}，将在 {} 执行", jobName, scheduleDate);
        
        return jobName;
    }

    /**
     * 创建一个重复执行的任务
     */
    public String createRepeatingJob(int intervalSeconds) throws SchedulerException {
        String jobName = "repeatingJob_" + System.currentTimeMillis();
        String jobGroup = "REPEATING_GROUP";
        
        // 定义任务
        JobDetail jobDetail = JobBuilder.newJob(SampleJob.class)
                .withIdentity(jobName, jobGroup)
                .withDescription("Repeating job with interval: " + intervalSeconds + "s")
                .storeDurably()
                .build();
        
        // 定义触发器 - 每intervalSeconds秒执行一次
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger_" + jobName, jobGroup)
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(intervalSeconds)
                        .repeatForever())
                .build();
        
        // 提交任务
        Date scheduleDate = scheduler.scheduleJob(jobDetail, trigger);
        logger.info("已创建重复任务: {}，将在 {} 开始执行，间隔 {} 秒", 
                jobName, scheduleDate, intervalSeconds);
        
        return jobName;
    }

    /**
     * 检查任务是否存在
     */
    public boolean checkJobExists(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        return scheduler.checkExists(jobKey);
    }

    /**
     * 暂停任务
     */
    public void pauseJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        scheduler.pauseJob(jobKey);
        logger.info("已暂停任务: {}:{}", jobGroup, jobName);
    }

    /**
     * 恢复任务
     */
    public void resumeJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        scheduler.resumeJob(jobKey);
        logger.info("已恢复任务: {}:{}", jobGroup, jobName);
    }

    /**
     * 删除任务
     */
    public void deleteJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroup);
        boolean deleted = scheduler.deleteJob(jobKey);
        if (deleted) {
            logger.info("已删除任务: {}:{}", jobGroup, jobName);
        } else {
            logger.warn("删除任务失败，任务不存在: {}:{}", jobGroup, jobName);
        }
    }
}
    